package cn.jn.lhm.part04;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;

/**
 * @author lhm 2753914576@qq.com
 * @time 2023/4/13 - 0:21
 **/
public class Server {
    public static void main(String[] args) throws Exception {
        Selector selector = Selector.open();

        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(8080));
        ssc.configureBlocking(false);
        ssc.register(selector, SelectionKey.OP_ACCEPT, null);

        while (true) {
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();

                if (key.isAcceptable()) {
                    SocketChannel client = ssc.accept();
                    client.configureBlocking(false);
                    SelectionKey clientKey = client.register(selector, SelectionKey.OP_READ, null);

                    StringBuilder builder = new StringBuilder();

                    for (int i = 0; i < 30000000; i++) {
                        builder.append("李");
                    }

                    // buffer对应的长度会超过Channel一次传输的大小，就让其继续触发写入事件
                    ByteBuffer buffer = Charset.defaultCharset().encode(builder.toString());

                    int count = client.write(buffer);
                    System.out.println(count);

                    if (buffer.hasRemaining()) {
                        clientKey.interestOps(clientKey.interestOps() + SelectionKey.OP_WRITE);
                        // 作为附件附加上去
                        clientKey.attach(buffer);
                    }
                } else if (key.isWritable()) {
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    SocketChannel channel = (SocketChannel) key.channel();
                    int count = channel.write(buffer);
                    System.out.println(count);

                    // 写完移除 Write事件
                    if (!buffer.hasRemaining()) {
                        key.interestOps(key.interestOps() - SelectionKey.OP_WRITE);
                    }
                }

                iterator.remove();
            }
        }
    }
}
